<template>
  <div class="card-wrap animate-on-enter">
    <a-tabs v-model:activeKey="activeTab" type="card" class="settings-tabs">
          <a-tab-pane key="profile" tab="个人信息">
            <div class="tab-content">
              <a-form
                ref="profileFormRef"
                :model="profileForm"
                :rules="profileRules"
                layout="vertical"
                class="profile-form"
              >
                <a-row :gutter="24">
                  <a-col :span="12">
                    <a-form-item label="用户名" name="username">
                      <a-input 
                        v-model:value="profileForm.username" 
                        placeholder="请输入用户名"
                        :disabled="true"
                      />
                      <div class="form-tip">用户名不可修改</div>
                    </a-form-item>
                  </a-col>
                  
                  <a-col :span="12">
                    <a-form-item label="真实姓名" name="real_name">
                      <a-input 
                        v-model:value="profileForm.real_name" 
                        placeholder="请输入真实姓名"
                      />
                    </a-form-item>
                  </a-col>
                  
                  <a-col :span="12">
                    <a-form-item label="邮箱" name="email">
                      <a-input 
                        v-model:value="profileForm.email" 
                        placeholder="请输入邮箱地址"
                        type="email"
                      />
                    </a-form-item>
                  </a-col>
                  

                  
                  <a-col :span="24">
                    <a-form-item label="个人简介" name="bio">
                      <a-textarea 
                        v-model:value="profileForm.bio" 
                        placeholder="请输入个人简介"
                        :rows="4"
                        :maxlength="200"
                        show-count
                      />
                    </a-form-item>
                  </a-col>
                </a-row>
                
                <div class="form-actions">
                  <a-button type="primary" @click="handleUpdateProfile" :loading="profileLoading">
                    <save-outlined /> 保存修改
                  </a-button>
                  <a-button @click="handleResetProfile">
                    <redo-outlined /> 重置
                  </a-button>
                </div>
              </a-form>
            </div>
          </a-tab-pane>
          
          <a-tab-pane key="password" tab="修改密码">
            <div class="tab-content">
              <a-form
                ref="passwordFormRef"
                :model="passwordForm"
                :rules="passwordRules"
                layout="vertical"
                class="password-form"
              >
                <a-row :gutter="24">
                  <a-col :span="12">
                    <a-form-item label="当前密码" name="current_password">
                      <a-input-password 
                        v-model:value="passwordForm.current_password" 
                        placeholder="请输入当前密码"
                        autocomplete="current-password"
                      />
                    </a-form-item>
                    
                    <a-form-item label="新密码" name="new_password">
                      <a-input-password 
                        v-model:value="passwordForm.new_password" 
                        placeholder="请输入新密码"
                        autocomplete="new-password"
                      />
                      <div class="form-tip">
                        密码必须包含字母、数字和特殊字符，长度6-20位
                      </div>
                    </a-form-item>
                    
                    <a-form-item label="确认新密码" name="confirm_password">
                      <a-input-password 
                        v-model:value="passwordForm.confirm_password" 
                        placeholder="请再次输入新密码"
                        autocomplete="new-password"
                      />
                    </a-form-item>
                  </a-col>
                  
                  <a-col :span="12">
                    <div class="password-tips">
                      <h4>密码安全建议：</h4>
                      <ul>
                        <li>密码长度至少6位，建议8位以上</li>
                        <li>包含大小写字母、数字和特殊字符</li>
                        <li>不要使用常见的密码组合</li>
                        <li>定期更换密码</li>
                        <li>不要在多个网站使用相同密码</li>
                      </ul>
                    </div>
                  </a-col>
                </a-row>
                
                <div class="form-actions">
                  <a-button type="primary" @click="handleChangePassword" :loading="passwordLoading">
                    <lock-outlined /> 修改密码
                  </a-button>
                  <a-button @click="handleResetPassword">
                    <redo-outlined /> 重置
                  </a-button>
                </div>
              </a-form>
            </div>
          </a-tab-pane>
          
          <a-tab-pane key="security" tab="安全设置">
            <div class="tab-content">
              <div class="security-section">
                <h3>登录安全</h3>
                <div class="security-item">
                  <div class="security-info">
                    <h4>最后登录时间</h4>
                    <p>{{ formatTime(userInfo.last_login_time) }}</p>
                  </div>
                </div>
                
                <div class="security-item">
                  <div class="security-info">
                    <h4>最后登录IP</h4>
                    <p>{{ userInfo.last_login_ip || '未知' }}</p>
                  </div>
                </div>
                
                <a-divider />
                
                <h3>账户状态</h3>
                <div class="security-item">
                  <div class="security-info">
                    <h4>账户状态</h4>
                    <a-tag :color="userInfo.status === 1 ? 'green' : 'red'">
                      {{ userInfo.status === 1 ? '正常' : '禁用' }}
                    </a-tag>
                  </div>
                </div>
                
                <div class="security-item">
                  <div class="security-info">
                    <h4>角色权限</h4>
                    <a-tag color="blue">
                      {{ userInfo.role?.name || '普通用户' }}
                    </a-tag>
                  </div>
                </div>
                
                <a-divider />
                
                <div class="danger-zone">
                  <h3>危险操作</h3>
                  <div class="security-item">
                    <div class="security-info">
                      <h4>注销账户</h4>
                      <p>注销后将无法恢复，请谨慎操作</p>
                    </div>
                    <a-button danger @click="handleDeleteAccount">
                      <delete-outlined /> 注销账户
                    </a-button>
                  </div>
                </div>
              </div>
            </div>
          </a-tab-pane>
        </a-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user.js'
import { message, Modal } from 'ant-design-vue'
import { updateProfile, changePassword } from '@/api/auth.js'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const activeTab = ref('profile')
const profileLoading = ref(false)
const passwordLoading = ref(false)
const profileFormRef = ref()
const passwordFormRef = ref()

// 表单数据
const profileForm = reactive({
  username: '',
  real_name: '',
  email: '',

  bio: ''
})

const passwordForm = reactive({
  current_password: '',
  new_password: '',
  confirm_password: ''
})

// 计算属性
const userInfo = computed(() => userStore.userInfo || {})

// 表单验证规则
const profileRules = {
  real_name: [
    { max: 20, message: '真实姓名不能超过20个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],

}

const passwordRules = {
  current_password: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur' },
    { 
      pattern: /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]+$/, 
      message: '密码必须包含字母、数字和特殊字符', 
      trigger: 'blur' 
    }
  ],
  confirm_password: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (value !== passwordForm.new_password) {
          return Promise.reject('两次输入的密码不一致')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ]
}

// 方法
const formatTime = (time) => {
  if (!time) return '未知'
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

const initProfileForm = () => {
  Object.assign(profileForm, {
    username: userInfo.value.username || '',
    real_name: userInfo.value.real_name || '',
    email: userInfo.value.email || '',

    bio: userInfo.value.bio || ''
  })
}

const handleUpdateProfile = async () => {
  try {
    await profileFormRef.value.validate()
    profileLoading.value = true
    
    const response = await updateProfile(profileForm)
    if (response.code === 200) {
      message.success('个人信息更新成功')
      // 更新store中的用户信息
      userStore.userInfo = { ...userStore.userInfo, ...profileForm }
    } else {
      message.error(response.message || '更新失败')
    }
  } catch (error) {
    console.error('更新个人信息失败:', error)
  } finally {
    profileLoading.value = false
  }
}

const handleResetProfile = () => {
  initProfileForm()
  profileFormRef.value?.clearValidate()
}

const handleChangePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true
    
    const response = await changePassword(passwordForm)
    if (response.code === 200) {
      message.success('密码修改成功，请重新登录')
      // 清空表单
      Object.assign(passwordForm, {
        current_password: '',
        new_password: '',
        confirm_password: ''
      })
      // 延迟跳转到登录页
      setTimeout(() => {
        userStore.outLogin()
      }, 1500)
    } else {
      message.error(response.message || '密码修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
  } finally {
    passwordLoading.value = false
  }
}

const handleResetPassword = () => {
  Object.assign(passwordForm, {
    current_password: '',
    new_password: '',
    confirm_password: ''
  })
  passwordFormRef.value?.clearValidate()
}

const handleDeleteAccount = () => {
  Modal.confirm({
    title: '确认注销账户？',
    content: '注销后账户数据将被永久删除，此操作不可恢复！',
    okText: '确认注销',
    okType: 'danger',
    cancelText: '取消',
    onOk() {
      message.info('账户注销功能暂未开放')
    }
  })
}

// 监听路由参数
watch(
  () => route.query.tab,
  (newTab) => {
    if (newTab && ['profile', 'password', 'security'].includes(newTab)) {
      activeTab.value = newTab
    }
  },
  { immediate: true }
)

// 监听用户信息变化
watch(
  () => userInfo.value,
  () => {
    initProfileForm()
  },
  { immediate: true, deep: true }
)

onMounted(() => {
  initProfileForm()
})
</script>

<style lang="less" scoped>
.settings-tabs {
  :deep(.ant-tabs-card .ant-tabs-tab) {
    border-radius: 6px 6px 0 0;
    
    &.ant-tabs-tab-active {
      background: #fff;
    }
  }
}

.tab-content {
  padding: 20px;
}

.profile-form,
.password-form {
  max-width: 600px;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.form-actions {
  display: flex;
  gap: 12px;
  margin-top: 20px;
}

.password-tips {
  background: #f6f8fa;
  border: 1px solid #e1e4e8;
  border-radius: 6px;
  padding: 16px;
  
  h4 {
    margin: 0 0 8px 0;
    color: #1a1a1a;
    font-weight: 600;
  }
  
  ul {
    margin: 0;
    padding-left: 16px;
    
    li {
      margin-bottom: 6px;
      color: #666;
      font-size: 13px;
      line-height: 1.4;
    }
  }
}

.security-section {
  max-width: 600px;
  
  h3 {
    margin: 0 0 12px 0;
    color: #1a1a1a;
    font-weight: 600;
    font-size: 15px;
  }
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.security-info {
  flex: 1;
  
  h4 {
    margin: 0 0 4px 0;
    color: #1a1a1a;
    font-weight: 500;
    font-size: 13px;
  }
  
  p {
    margin: 0;
    color: #666;
    font-size: 13px;
  }
}

.danger-zone {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 2px solid #ff4d4f;
  
  h3 {
    color: #ff4d4f;
  }
}

@media (max-width: 768px) {
  .tab-content {
    padding: 12px;
  }
  
  .security-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>